package leetcode.editor.cn;

public class P450DeleteNodeInABst {
    public static void main(String[] args) {
        Solution solution = new P450DeleteNodeInABst().new Solution();
        TreeNode treeNode = new TreeNode(4);
        treeNode.right = new TreeNode(7);
        treeNode.right.left = new TreeNode(6);
        treeNode.right.right = new TreeNode(8);
        treeNode.right.left.left = new TreeNode(5);
        treeNode.right.right.right = new TreeNode(9);
        solution.deleteNode(treeNode, 7);
        System.out.println();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return root;
            }
            if (root.val == key) {
                if (root.left == null && root.right == null) {
                    return null;
                }
                if (root.right == null) {
                    return root.left;
                }
                if (root.left == null) {
                    return root.right;
                }

                TreeNode max = getRightMax(root.right);
                root.right = deleteNode(root.right, max.val);
                max.right = root.right;
                max.left = root.left;
                return max;

            } else if (root.val > key) {
                root.left = deleteNode(root.left, key);
            } else {
                root.right = deleteNode(root.right, key);
            }
            return root;
        }

        TreeNode getLeftMax(TreeNode root) {
            if (root == null) {
                return null;
            }
            if (root.left == null && root.right == null) {
                return root;
            }
            if (root.right == null) {
                return root;
            }
            return getLeftMax(root.right);
        }

        TreeNode getRightMax(TreeNode root) {
            if (root == null) {
                return null;
            }
            if (root.left == null && root.right == null) {
                return root;
            }
            if (root.left == null) {
                return root;
            }
            return getRightMax(root.left);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}